package cn.coder.jdbc.spring;

import javax.sql.DataSource;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import cn.coder.jdbc.SqlSessionFactory;
import cn.coder.jdbc.util.Assert;

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {

	private DataSource dataSource;
	private SqlSessionFactory sqlSessionFactory;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public SqlSessionFactory getObject() throws Exception {
		Assert.notNull(this.sqlSessionFactory, "Property 'sqlSessionFactory' is required");
		return this.sqlSessionFactory;
	}

	@Override
	public Class<?> getObjectType() {
		return SqlSessionFactory.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// 如果没有配置外部的数据源，则引用内部数据源
		if (this.dataSource == null) {
			SqlSessionFactory.createSessions();
		} else {
			SqlSessionFactory.createSession(this.dataSource);
		}
		this.sqlSessionFactory = SqlSessionFactory.getInstance();
	}

}
